package cn.caplike.demo.rabbitmq.api.exchange.default_;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import static cn.caplike.demo.rabbitmq.api.Application.RABBITMQ_HOST;
import static cn.caplike.demo.rabbitmq.api.Application.RABBITMQ_PORT;

/**
 * Default Exchange
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2020-02-18 14:43
 */
public class Producer4DefaultExchange {
    private static final String ROUTING_KEY = "test001";

    public static void main(String[] args) throws IOException, TimeoutException {
        // 创建一个链接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(RABBITMQ_HOST);
        connectionFactory.setPort(RABBITMQ_PORT);
        connectionFactory.setVirtualHost("/");

        // 通过链接工厂创建连接
        Connection connection = connectionFactory.newConnection();

        // 通过连接创建一个 Channel
        Channel channel = connection.createChannel();

        // 通过 Channel 发送数据
        for (int idx = 0; idx < 5; idx++) {
            // 如果不指定 Exchange, 会使用默认的交换机 (Default Exchange), 按照 routingKey 找到同名的 queue, 然后路由过去
            channel.basicPublish(
                    "", ROUTING_KEY, null, "Hello RabbitMQ!".getBytes()
            );
        }

        // 关闭连接
        channel.close();
        connection.close();
    }

}
